<?php

namespace app\admin\controller\notice;

use addons\notice\library\NoticeClient;
use app\admin\model\Admin;
use app\admin\model\notice\Notice;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;

require_once ROOT_PATH . '/addons/notice/library/common/helper.php';

class Noticesendrecode extends Backend
{
    protected $model = null;

    protected $searchFields = ['id','name','event'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\notice\Noticesendrecode;
        $this->assignconfig("typeList", $this->model->getTypeList());
        $this->view->assign("visibleSwitchList", $this->model->getVisibleSwitchList());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['admin'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['admin_id'] = $this->auth->id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success('', null, $this->model->id);
    }

    public function edit($ids = null)
    {
        // copy数据
        if ($this->request->isPost() && input('is_copy')) {
            $params = $this->request->post("row/a");
            $params = $this->preExcludeFields($params);
            $this->model->save($params);
            $this->success('添加成功');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('', null, $row->id);
        // return parent::edit($ids);
    }

    public function send($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $params = input('row/a');
            $params = $this->preExcludeFields($params);
            $params = array_only($params, '*');
            $params['field']['receiver_admin_ids']  = input('row.receiver_admin_ids');
            $params['field']['receiver_admin_group_ids']  = input('row.receiver_admin_group_ids');
            $params['field'] = array_filter($params['field'], function ($v) {
                return $v != '';
            });
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            if(!isset($params['field']['receiver_admin_ids']) && !isset($params['field']['receiver_admin_group_ids'])){
                $this->error(__('请选择发送人'));
            }
            Db::startTrans();
            try{
                // 函数发送

                // 添加消息记录
                $noticeData = [
                    'name' => $row['name'],
                    'event' => $row['id'],
                    'platform' => 'admin',
                    'type' => $row['type'],
                    'to_id' => 0,
                    'content' => $row['content'],
                    'ext' => '',
                    'notice_template_id' => $row['id']
                ];
                $to_id1 = $to_id2 = [];
                // 批量发送情况
                if(isset($params['field']['receiver_admin_ids'])){
                    $to_id1 = [$params['field']['receiver_admin_ids']];
                }
                if(isset($params['field']['receiver_admin_group_ids'])){
                    $to_id2 = Admin::join('auth_group_access', 'auth_group_access.uid = id')
                        ->where('group_id', 'in', $params['field']['receiver_admin_group_ids'])
                        ->column('id');
                }
                $to_id = array_unique(array_merge($to_id1,$to_id2));
//                $to_id = is_array($noticeData['to_id']) ? $noticeData['to_id'] : [$noticeData['to_id']];

                foreach ($to_id as $v2) {
                    $noticeData['to_id'] = $v2;
                    Notice::create($noticeData);
                    $row->setInc('send_adminnum');
                }
                $is = $row->setInc('send_num');

                Db::commit();
            }catch (\Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
            }
            if ($is) {
                $this->success('操作成功');
            }
            $this->error('发送失败:'.NoticeClient::instance()->getError());
        }

        $this->assign('row', $row);

        return $this->fetch();
    }
}